<template>
	<xn-form-container title="新增调解协议" :width="800" :visible="visible" :destroy-on-close="true" @close="onClose">
		<a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
			<a-row :gutter="24">
				<a-col :span="12">
					<a-form-item label="欠款人姓名" name="debtorName">
						<a-input v-model:value="formData.debtorName" placeholder="请输入欠款人姓名" />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="欠款人身份证号" name="debtorCardId">
						<a-input v-model:value="formData.debtorCardId" placeholder="请输入欠款人身份证号" />
					</a-form-item>
				</a-col>
			</a-row>
			<a-row :gutter="24">
				<a-col :span="12">
					<a-form-item label="调解函号" name="mediationNum">
						<a-input v-model:value="formData.mediationNum" placeholder="请输入调解函号" />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="借款金额" name="loanAmount">
						<a-input-number
							v-model:value="formData.loanAmount"
							placeholder="请输入借款金额"
							:min="0"
							:precision="2"
							style="width: 100%"
						/>
					</a-form-item>
				</a-col>
			</a-row>
			<a-row :gutter="24">
				<a-col :span="12">
					<a-form-item label="调解状态" name="mediationStatus">
						<a-select
							v-model:value="formData.mediationStatus"
							placeholder="请选择调解状态"
							:options="mediationStatusOptions"
						/>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="诉讼状态" name="litigationStatus">
						<a-select
							v-model:value="formData.litigationStatus"
							placeholder="请选择诉讼状态"
							:options="litigationStatusOptions"
						/>
					</a-form-item>
				</a-col>
			</a-row>
			<a-row :gutter="24">
				<a-col :span="12">
					<a-form-item label="平台" name="platform">
						<a-input v-model:value="formData.platform" placeholder="请输入平台" />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="产品" name="product">
						<a-input v-model:value="formData.product" placeholder="请输入产品" />
					</a-form-item>
				</a-col>
			</a-row>
			<a-row :gutter="24">
				<a-col :span="12">
					<a-form-item label="案件日期" name="caseDate">
						<a-date-picker v-model:value="formData.caseDate" placeholder="请选择案件日期" style="width: 100%" />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="调解协议出具日期" name="mediationLetterDate">
						<a-date-picker
							v-model:value="formData.mediationLetterDate"
							placeholder="请选择调解协议出具日期"
							style="width: 100%"
						/>
					</a-form-item>
				</a-col>
			</a-row>
			<a-row :gutter="24">
				<a-col :span="12">
					<a-form-item label="调解员" name="mediatorName">
						<a-input v-model:value="formData.mediatorName" placeholder="请输入调解员" />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="调解员电话" name="mediationPersonPhone">
						<a-input v-model:value="formData.mediationPersonPhone" placeholder="请输入调解员电话" />
					</a-form-item>
				</a-col>
			</a-row>
			<a-row :gutter="24">
				<a-col :span="12">
					<a-form-item label="调解中心电话" name="mediationCenterPhone">
						<a-input v-model:value="formData.mediationCenterPhone" placeholder="请输入调解中心电话" />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="监督举报电话" name="supervisionPhone">
						<a-input v-model:value="formData.supervisionPhone" placeholder="请输入监督举报电话" />
					</a-form-item>
				</a-col>
			</a-row>
			<a-row :gutter="24">
				<a-col :span="12">
					<a-form-item label="有效期" name="expiryDate">
						<a-date-picker v-model:value="formData.expiryDate" placeholder="请选择有效期" style="width: 100%" />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="调解中心" name="companyName">
						<a-select v-model:value="formData.companyName" placeholder="请选择调解中心" @change="handleCenterChange">
							<a-select-option
								v-for="option in tjCenterList"
								:key="option.id"
								:value="option.id"
								:label="option.companyName"
							>
								{{ option.companyName }}
							</a-select-option>
						</a-select>
					</a-form-item>
				</a-col>
			</a-row>
			<a-row :gutter="24">
				<a-col :span="12">
					<a-form-item label="调解中心官网" name="officialWebsite">
						<a-input v-model:value="formData.officialWebsite" placeholder="请输入调解中心官网" />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="微信公众号" name="weChatOfficialAccount">
						<a-input v-model:value="formData.weChatOfficialAccount" placeholder="请输入微信公众号" />
					</a-form-item>
				</a-col>
			</a-row>
			<a-row :gutter="24">
				<a-col :span="12">
					<a-form-item label="省份简称" name="provAbbr">
						<a-input v-model:value="formData.provAbbr" placeholder="请输入省份简称" />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="公章URL" name="officialSealUrl">
						<!-- 显示公章图片 -->
						<img
							v-if="formData.officialSealUrl"
							:src="formData.officialSealUrl"
							alt="公章"
							style="max-width: 100%; max-height: 200px"
						/>
						<a-input v-model:value="formData.officialSealUrl" placeholder="请输入公章URL" v-else />
					</a-form-item>
				</a-col>
			</a-row>
		</a-form>
		<template #footer>
			<a-button class="xn-mr8" @click="onClose">关闭</a-button>
			<a-button type="primary" @click="onSubmit" :loading="submitLoading">保存</a-button>
		</template>
	</xn-form-container>
</template>

<script setup>
	import { reactive, ref } from 'vue'
	import { message } from 'ant-design-vue'
	import { required } from '@/utils/formRules'
	import tool from '@/utils/tool'
	import dayjs from 'dayjs'
	import mediationProtocolApi from '@/api/website/protocol/mediationProtocolApi'
	import configApi from '@/api/website/config/configApi'

	// 组件状态
	const visible = ref(false)
	const submitLoading = ref(false)
	const formRef = ref()
	const emit = defineEmits(['successful'])

	// 选项数据
	const mediationStatusOptions = tool.dictList('MEDIATION_STATUS')
	const litigationStatusOptions = tool.dictList('LITIGATION_STATUS')
	const tjCenterList = ref([])

	// 表单数据结构
	const initialFormData = {
		companyName: undefined, // 调解中心名称
		debtorName: undefined, // 欠款人姓名
		debtorCardId: undefined, // 欠款人身份证号
		mediationStatus: undefined, // 调解状态
		mediationNum: undefined, // 调解函号
		platform: undefined, // 平台
		product: undefined, // 产品编码
		loanAmount: undefined, // 借款金额
		caseDate: undefined, // 案件日期
		officialWebsite: undefined, // 调解中心官网
		officialSealUrl: undefined, // 公章URL
		weChatOfficialAccount: undefined, // 微信公众号
		mediatorName: undefined, // 调解员
		mediationPersonPhone: undefined, // 调解员电话
		mediationCenterPhone: undefined, // 调解中心电话
		supervisionPhone: undefined, // 监督举报电话
		mediationLetterDate: undefined, // 调解协议出具日期
		litigationStatus: undefined, // 诉讼状态
		expiryDate: undefined // 有效期
	}
	const formData = ref({ ...initialFormData })

	// 验证规则，按照表单字段顺序排序
	const formRules = reactive({
		debtorName: [required('欠款人姓名')],
		provAbbr: [required('省份简称')],
		debtorCardId: [required('欠款人身份证号'), { pattern: /^\d{17}[\dXx]$/, message: '请输入正确的身份证号码' }],
		mediationNum: [required('调解函号')],
		loanAmount: [required('借款金额'), { type: 'number', min: 0, message: '金额必须大于0' }],
		mediationStatus: [required('调解状态')],
		litigationStatus: [required('诉讼状态')],
		platform: [required('平台')],
		product: [required('产品')],
		caseDate: [required('案件日期')],
		mediationLetterDate: [required('调解协议出具日期')],
		mediatorName: [required('调解员')],
		// mediationPersonPhone: [required('调解员电话'), { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码' }],
		companyName: [required('调解中心名称')],
		officialWebsite: [required('调解中心官网'), { type: 'url', message: '请输入正确的网址' }],
		mediationCenterPhone: [
			required('调解中心电话'),
			{ pattern: /^0\d{2,3}-\d{7,8}$|^1[3-9]\d{9}$/, message: '请输入正确的电话号码' }
		],
		supervisionPhone: [
			required('监督举报电话'),
			{ pattern: /^0\d{2,3}-\d{7,8}$|^1[3-9]\d{9}$/, message: '请输入正确的电话号码' }
		],
		officialSealUrl: [required('公章URL')],
		weChatOfficialAccount: [required('微信公众号')],
		expiryDate: [required('有效期')]
	})

	const onOpen = (record) => {
		configApi.listAll().then((res) => {
			tjCenterList.value = res
		})
		// 如果有记录，则填充表单数据（编辑模式）
		if (record) {
			formData.value = {
				...record,
				caseDate: record.caseDate ? dayjs(record.caseDate) : undefined,
				mediationLetterDate: record.mediationLetterDate ? dayjs(record.mediationLetterDate) : undefined,
				expiryDate: record.expiryDate ? dayjs(record.expiryDate) : undefined
			}
		} else {
			// 重置表单（新增模式）
			formData.value = { ...initialFormData }
			formRef.value?.resetFields()
		}
		visible.value = true
	}

	// 表单重置
	const onClose = () => {
		formData.value = { ...initialFormData }
		formRef.value?.resetFields()
		visible.value = false
	}

	const handleCenterChange = (value) => {
		const selectedCenter = tjCenterList.value.find((item) => item.id === value)
		if (selectedCenter) {
			console.log(selectedCenter)
			formData.value.companyName = selectedCenter.companyName
			formData.value.weChatOfficialAccount = selectedCenter.weChatOfficialAccount
			formData.value.officialWebsite = selectedCenter.websiteUrl
			formData.value.officialSealUrl = selectedCenter.officialSealUrl
			formData.value.provAbbr = selectedCenter.provAbbr
		}
	}

	// 表单提交
	const onSubmit = () => {
		formRef.value
			.validate()
			.then(() => {
				try {
					submitLoading.value = true
					const submitData = {
						...formData.value,
						// 转换日期格式
						caseDate: formData.value.caseDate ? formData.value.caseDate.format('YYYY-MM-DD') : null,
						mediationLetterDate: formData.value.mediationLetterDate
							? formData.value.mediationLetterDate.format('YYYY-MM-DD')
							: null,
						expiryDate: formData.value.expiryDate ? formData.value.expiryDate.format('YYYY-MM-DD') : null
					}
					if (submitData.id) {
						mediationProtocolApi.edit(submitData).then((res) => {
							message.success('保存成功')
							emit('successful', res)
							onClose()
						})
					} else {
						mediationProtocolApi.add(submitData).then((res) => {
							message.success('保存成功')
							emit('successful', res)
							onClose()
						})
					}
				} catch (e) {
					submitLoading.value = false
				}
			})
			.catch(() => {
				submitLoading.value = false
			})
	}

	defineExpose({
		onOpen
	})
</script>
